package com.weiyin.examination.activity;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.weiyin.examination.R;
import com.weiyin.examination.application.Constant;
import com.weiyin.examination.http.DataService;
import com.weiyin.examination.http.HttpRequestListener;
import com.weiyin.examination.http.RequestUrl;
import com.weiyin.examination.http.RetrofitClient;
import com.weiyin.examination.module.Mp3Module;
import com.weiyin.examination.module.TestModule;
import com.weiyin.examination.util.LayoutHelper;
import com.weiyin.examination.util.LogUtil;
import com.weiyin.examination.util.SPUtil;
import com.weiyin.examination.util.VerifyCodeUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observer;

/**
 * 加载数据界面
 *
 * @author njf
 */
public class LoadingActivity extends BaseActivity implements View.OnClickListener,
        HttpRequestListener<ResponseBody> {
    private String TAG = LoadingActivity.class.getSimpleName();
    private ImageView loadingImageView;
    private Button loadingStart;
    private AnimationDrawable animationDrawable;
    private DataService dataService;
    private ArrayList<TestModule> testModuleList;

    Handler mHandler = new Handler();
    private boolean isStart = true;
    private String level, number, paperType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);
        LayoutHelper layoutHelper = new LayoutHelper(this);
        layoutHelper.scaleView(findViewById(R.id.loadingActivityLayout));
        testModuleList = new ArrayList<>();

        level = SPUtil.getSharedPreferencesData(this, "level", "");
        number = SPUtil.getSharedPreferencesData(this, "number", "");
        paperType = SPUtil.getSharedPreferencesData(this, "paperType", "");

        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isStart = true;
    }

    @Override
    protected void onDestroy() {
        if (animationDrawable != null) {
            animationDrawable.stop();
        }
        super.onDestroy();
    }

    public void initView() {
        dataService = new DataService(RetrofitClient.getInstance(this).getService());

        loadingStart = (Button) findViewById(R.id.loadingStart);
        loadingImageView = (ImageView) findViewById(R.id.loadingImageView);
        loadingStart.setOnClickListener(this);
    }

    private void initData() {
        dataService.getPaper(number, paperType, level, this);
    }


    private void down() {
        for (int i = 0; i < testModuleList.size(); i++) {
            List<Mp3Module> mp3List = testModuleList.get(i).getMp3UrlList();
            for (int j = 0; j < mp3List.size(); j++) {
                if (mp3List.get(j).getMp3Url() != null) {
                    String fileUrl = mp3List.get(j).getMp3Url();
                    final File futureStudioIconFile = new File(LoadingActivity.this.getApplicationContext().getExternalFilesDir(null) + fileUrl.replace("/", ""));
                    LogUtil.i(TAG, "filePath=" + (LoadingActivity.this.getApplicationContext().getExternalFilesDir(null) + fileUrl.replace("/", "")) + " futureStudioIconFile.exists()=" + futureStudioIconFile.exists());
                    if (!futureStudioIconFile.exists()) {
                        dataService.down(mp3List.get(j).getMp3Url(), new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                if (response.isSuccessful()) {
                                    LogUtil.i(TAG, "server contacted and has file");

                                    boolean writtenToDisk = dataService.writeResponseBodyToDisk(response.body(), futureStudioIconFile);
                                    LogUtil.i(TAG, "file download was a success? " + writtenToDisk);
                                    if (!writtenToDisk) {
                                        Constant.showTextToast(LoadingActivity.this.getApplicationContext(), "MP3文件下载失败");
                                    }
                                } else {
                                    LogUtil.i(TAG, "server contact failed");
                                }
                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                Constant.showTextToast(LoadingActivity.this.getApplicationContext(), "MP3文件下载失败");
                            }
                        });
                    }
                }
            }
        }
        observer.onCompleted();
    }


    private void skip() {
        if (isStart) {
            isStart = false;
            loadingStart.setText("开始考试");
            loadingStart.setEnabled(true);

            if (animationDrawable != null) {
                animationDrawable.stop();
            }
            loadingImageView.setImageResource(R.drawable.wait);

            Intent intent = new Intent();
            intent.putParcelableArrayListExtra("list", testModuleList);
            intent.setClass(LoadingActivity.this, TopicActivity.class);
            this.startActivity(intent);
            LogUtil.i(TAG, "skip");
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loadingStart:
                VerifyCodeUtils.sendButtonCode(this, loadingStart, 60, observer);
                loadingImageView.setImageResource(R.drawable.imageview_rotate);
                animationDrawable = new AnimationDrawable();
                animationDrawable = (AnimationDrawable) loadingImageView.getDrawable();
                animationDrawable.start();

                initData();
                break;
            default:
                break;
        }
    }

    Observer<Long> observer = new Observer<Long>() {
        @Override
        public void onCompleted() {
            //数据发送完后设置为原来的文字
            skip();
        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
        }

        @Override
        public void onNext(Long aLong) {
            //接受到一条就是会操作一次UI
            loadingStart.setText(format(aLong));
        }
    };

    private String format(long timeLength) {
        long m = timeLength / 60;
        timeLength = timeLength % 60;
        String min = String.valueOf(timeLength);
        String hour = String.valueOf(m);
        if (m < 10) {
            hour = "0" + hour;
        }
        if (timeLength < 10) {
            min = "0" + min;
        }
        return hour + ":" + min;
    }

    @Override
    public void onCompleted(String url) {
        LogUtil.i(TAG, "onCompleted url=" + url);
    }

    @Override
    public void onError(Throwable e, String url) {
        LogUtil.i(TAG, "onError " + e.getMessage() + " url=" + url);
    }

    @Override
    public void onNext(ResponseBody responseBean, String url) {
        switch (url) {
            case RequestUrl.PATH_APP:
                try {
                    String json = responseBean.string();
                    LogUtil.i(TAG, json);
                    JSONObject jsonObject = new JSONObject(json);
                    if (jsonObject.getInt(Constant.RESP_CODE) == 0) {
                        String tickNumber = jsonObject.getString("ticketNumber");
                        Gson gson = new Gson();
                        JSONArray jsonArray = jsonObject.getJSONArray("subjectList");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            TestModule homeTitleBean = gson.fromJson(jsonArray.getJSONObject(i).toString(), TestModule.class);
                            homeTitleBean.setTickNumber(tickNumber);
                            testModuleList.add(homeTitleBean);
                        }
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                down();
                            }
                        });
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }
}
